import { EventDetail } from '@/api';
import { ExpertSceneDetail } from '@/api/expert';
import {
  OrderAppointmentList,
  OrderAppointmentListrProps,
  OrderChargeList,
  OrderCount,
  OrderEventList,
  OrderEventListProps,
  OrderStatus,
} from '@/api/order';
import Empty from '@/components/Empty';
import StatusIconPrimary from '@/components/StatusIconPrimary';
import { Button, Icon, Tab, Tabs, Tag } from '@antmjs/vantui';
import { Image, Text, View } from '@tarojs/components';
import Taro, { useDidShow, useLoad } from '@tarojs/taro';
import { useState } from 'react';
import { useRequest, useVisible } from 'taro-hooks';
import useInvitationCode from '../activity/components/useInvitationCode';
import useCode from '../index/components/useCode';
import useReservationSuccess from '../professional/components/useReservationSuccess';
import './index.module.less';

export default function Page() {
  // ?页面是否显示
  const pageVisible = useVisible();

  // ?订单数量
  const { data: orderCount } = useRequest(OrderCount, {
    refreshDeps: [pageVisible],
  });

  //咨询订单
  const { data: appointment } = useRequest(
    () => OrderAppointmentList({ type: 1 }),
    {
      refreshDeps: [pageVisible],
    }
  );

  // ?咨询订单核销码
  const [appointmentRecord, setAppointmentRecord] =
    useState<OrderAppointmentListrProps>();
  const { renderNode: renderSuccessNode, open: openAppointSuccess } =
    useReservationSuccess({
      code: appointmentRecord?.code!,
      time: appointmentRecord?.appoint_time!,
      address: appointmentRecord?.address!,
      onClose: function () {
        setAppointmentRecord(undefined);
      },
    });

  // 活动订单
  const { data: eventlist } = useRequest(OrderEventList, {
    refreshDeps: [pageVisible],
  });

  // 服务订单
  const { data: serviceList } = useRequest(
    () => OrderAppointmentList({ type: 2 }),
    {
      refreshDeps: [pageVisible],
    }
  );

  // ?查看活动订单的核销码
  const [eventOrderRecord, setEventOrderRecord] =
    useState<OrderEventListProps>();
  const { data: eventDetail } = useRequest(
    () => EventDetail({ event_id: eventOrderRecord?.event_id! }),
    {
      ready: eventOrderRecord?.event_id ? true : false,
      onSuccess: function () {
        openInvitationCode();
      },
    }
  );

  //活动查看核销码
  const { renderNode: renderInvitaion, open: openInvitationCode } =
    useInvitationCode({
      detail: eventDetail!,
      onClose: function () {
        setEventOrderRecord(undefined);
      },
    });

  //服务订单查看核销码
  const [serviceOrderRecord, setServiceOrderRecord] =
    useState<OrderAppointmentListrProps>();
  const { data: sceneDetail } = useRequest(
    () => ExpertSceneDetail({ sceneId: serviceOrderRecord?.scene_id! }),
    {
      ready: serviceOrderRecord?.scene_id ? true : false,
      onSuccess: function () {
        openServiceCode();
      },
    }
  );

  const { renderNode: renderServiceNode, open: openServiceCode } = useCode({
    detail: sceneDetail!,
    onClose: function () {
      setServiceOrderRecord(undefined);
    },
  });

  return (
    <>
      <Tabs sticky animated>
        <Tab
          title={
            <>
              <View className='inline-block relative'>
                活动订单
                {Boolean(orderCount?.event) && (
                  <Tag
                    type='danger'
                    textColor='white'
                    round
                    className=' absolute -right-2 top-1'
                  >
                    {orderCount?.event}
                  </Tag>
                )}
              </View>
            </>
          }
        >
          <View className='p-2'>
            {/* empty */}

            {Boolean(!eventlist?.length) && (
              <View className='py-[180px]'>
                <Empty
                  icon={
                    <Image
                      src='https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/status-2.png'
                      className=' w-[381px] h-[311px] block -mb-[50px]'
                    />
                  }
                  title='暂无活动订单'
                  desc='暂时没有活动订单记录，您可以前去查看相关服务'
                >
                  <Button
                    type='primary'
                    className='w-[420px]'
                    onClick={() => {
                      Taro.switchTab({
                        url: `/pages/activity/index`,
                      });
                    }}
                  >
                    去查看
                  </Button>
                </Empty>
              </View>
            )}

            {eventlist?.map((item) => (
              <View
                key={item.id}
                className='mb-2'
                onClick={() => {
                  Taro.navigateTo({
                    url: `/pages/order/activityDetail?id=${item.event_id}`,
                  });
                }}
              >
                <View className='p-3 px-4 bg-white rounded-lg'>
                  <View className='flex text-black items-center mb-2'>
                    <Text className='mr-auto font-bold text-[36px]'>
                      {item.event_name}
                    </Text>
                    <Text className=' text-2xl font-bold leading-none mr-1'>
                      {item.beans}
                    </Text>
                    <Text className=' text-xs'>帮豆</Text>
                  </View>
                  <View className='flex items-center'>
                    <View className='flex-1'>
                      <Text className=' text-xs text-gary3 block mt-1'>
                        订单编号：{item.no}
                      </Text>
                      <Text className=' text-xs text-gary3 block mt-1'>
                        创建时间：{item.create_time}
                      </Text>
                    </View>
                    <Icon name='arrow' className='ml-auto text-md text-gary3' />
                  </View>
                </View>
                <View className='py-3 px-4 bg-[#F9FBFC] flex rounded-lg text-xs'>
                  <StatusIconPrimary />
                  {item.status === 2 && (
                    <View className=' text-gary4 flex items-center'>
                      <Icon name='clear' className=' mr-1' />
                      已取消
                    </View>
                  )}
                  {item.status === 1 && (
                    <View className='text-success flex items-center'>
                      <Icon name='checked' className=' mr-1' />
                      已完成
                    </View>
                  )}
                  {item.status === 0 && (
                    <View className=' flex items-center'>
                      <View
                        className='w-[162px] h-[36px] leading-[36px] pl-[16px] text-xs text-white mr-1'
                        style={{
                          backgroundImage: `url(https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/icon-warn-look.svg)`,
                          backgroundSize: '100% 100%',
                        }}
                        onClick={(e) => {
                          e.stopPropagation();
                          setEventOrderRecord(item);
                        }}
                      >
                        查看核销码
                      </View>
                      <View className='text-warn flex items-center'>
                        <Icon name='clock' className=' mr-1' />
                        待核销
                      </View>
                    </View>
                  )}
                </View>
              </View>
            ))}
          </View>
        </Tab>

        <Tab
          title={
            <>
              <View className=' inline-block relative'>
                服务订单
                {Boolean(orderCount?.scene) && (
                  <Tag
                    type='danger'
                    textColor='white'
                    round
                    className=' absolute -right-2 top-1'
                  >
                    {orderCount?.scene}
                  </Tag>
                )}
              </View>
            </>
          }
        >
          <View className='p-2'>
            {/* empty */}

            {Boolean(!serviceList?.length) && (
              <View className='py-[180px]'>
                <Empty
                  icon={
                    <Image
                      src='https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/status-2.png'
                      className=' w-[381px] h-[311px] block -mb-[50px]'
                    />
                  }
                  title='暂无服务订单'
                  desc='暂时没有服务记录，您可以前去查看相关服务'
                >
                  <Button
                    type='primary'
                    className='w-[420px]'
                    onClick={() => {
                      Taro.switchTab({
                        url: `/pages/index/index`,
                      });
                    }}
                  >
                    去查看
                  </Button>
                </Empty>
              </View>
            )}

            {serviceList?.map((item) => (
              <View
                key={item.id}
                className='mb-2'
                onClick={() => {
                  if (item.status === 0)
                    return Taro.showModal({
                      title: '系统提示',
                      content: '预约确认中，确认后可查看详情',
                      showCancel: false,
                    });

                  Taro.navigateTo({
                    url: `/pages/my/reservation/detail?id=${item.id}`,
                  });
                }}
              >
                <View className='p-3 px-4 bg-white rounded-lg'>
                  <View className='flex text-black items-center mb-2'>
                    <Text className='mr-auto font-bold text-[36px]'>
                      {item.name}
                    </Text>
                    <Text className=' text-2xl font-bold leading-none mr-1'>
                      {item.beans}
                    </Text>
                    <Text className=' text-xs'>帮豆</Text>
                  </View>
                  <View className='flex items-center'>
                    <View className='flex-1'>
                      <Text className=' text-xs text-gary3 block mt-1'>
                        订单编号：{item.no}
                      </Text>
                      <Text className=' text-xs text-gary3 block mt-1'>
                        创建时间：{item.create_time}
                      </Text>
                      <Text className=' text-xs text-gary3 block mt-1'>
                        服务时间：{item.appoint_time}
                      </Text>
                    </View>
                  </View>
                </View>
                <View className='py-3 px-4 bg-[#F9FBFC] flex rounded-lg text-xs'>
                  <StatusIconPrimary />
                  {item.status === 2 && (
                    <View className=' text-gary4 flex items-center'>
                      <Icon name='clear' className=' mr-1' />
                      已取消
                    </View>
                  )}
                  {item.status === 1 && (
                    <View className=' flex items-center'>
                      <View
                        className='w-[162px] h-[36px] leading-[36px] pl-[16px] text-xs text-white mr-1'
                        style={{
                          backgroundImage: `url(https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/icon-warn-look.svg)`,
                          backgroundSize: '100% 100%',
                        }}
                        onClick={(e) => {
                          e.stopPropagation();
                          setServiceOrderRecord(item);
                        }}
                      >
                        查看核销码
                      </View>
                      <View className='text-warn flex items-center'>
                        <Icon name='clock' className=' mr-1' />
                        待核销
                      </View>
                    </View>
                  )}
                  {item.status === 3 && (
                    <>
                      {(item.user_estimate && (
                        <View className='text-success flex items-center'>
                          <Icon name='checked' className=' mr-1' />
                          已完成
                        </View>
                      )) || (
                        <View className=' text-primary flex items-center'>
                          <Tag
                            type='warning'
                            className=' text-[20px] text-white mr-2 font-semibold'
                          >
                            ·完成评价可得{item.points}积分
                          </Tag>
                          <Icon name='thumb-circle' className=' mr-1' />
                          待评价
                        </View>
                      )}
                    </>
                  )}
                  {item.status === 0 && (
                    <>
                      <View className='text-warn flex items-center'>
                        <Icon name='clock' className=' mr-1' />
                        待确认
                      </View>
                    </>
                  )}
                </View>
              </View>
            ))}
          </View>
        </Tab>

        <Tab
          title={
            <>
              <View className='inline-block relative'>
                咨询订单
                {Boolean(orderCount?.appoint) && (
                  <Tag
                    type='danger'
                    textColor='white'
                    round
                    className=' absolute -right-2 top-1'
                  >
                    {orderCount?.appoint}
                  </Tag>
                )}
              </View>
            </>
          }
        >
          {Boolean(!appointment?.length) && (
            <View className='py-[180px]'>
              <Empty
                icon={
                  <Image
                    src='https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/status-2.png'
                    className=' w-[381px] h-[311px] block -mb-[50px]'
                  />
                }
                title='暂无咨询订单'
                desc='暂时没有咨询订单记录，您可以前去查看相关服务'
              >
                <Button
                  type='primary'
                  className='w-[420px]'
                  onClick={() => {
                    Taro.switchTab({
                      url: '/pages/professional/index',
                    });
                  }}
                >
                  去查看
                </Button>
              </Empty>
            </View>
          )}
          <View className='p-2'>
            {appointment?.map((item) => (
              <View
                className='mb-2'
                key={item.id}
                onClick={() => {
                  if (item.status === OrderStatus.待预约)
                    return Taro.showModal({
                      title: '系统提示',
                      content: '预约确认中，确认后可查看详情',
                      showCancel: false,
                    });

                  Taro.navigateTo({
                    url: `/pages/my/reservation/detail?id=${item.id}`,
                  });
                }}
              >
                <View className='p-3 px-4 bg-white rounded-lg'>
                  <View className='flex text-black items-center mb-2'>
                    <Text className='mr-auto font-bold text-[36px]'>
                      {item.name}
                    </Text>
                    <Text className=' text-2xl font-bold leading-none mr-1'>
                      {item.beans}
                    </Text>
                    <Text className=' text-xs'>帮豆</Text>
                  </View>
                  <View className='flex items-center'>
                    <View className='flex-1'>
                      <Text className=' text-xs text-gary3 block mt-1'>
                        订单编号：{item.no}
                      </Text>
                      <Text className=' text-xs text-gary3 block mt-1'>
                        创建时间：{item.create_time}
                      </Text>
                      <Text className=' text-xs text-gary3 block mt-1'>
                        服务时间：{item.appoint_time}
                      </Text>
                    </View>
                    <Icon name='arrow' className='ml-auto text-md text-gary3' />
                  </View>
                </View>
                <View className='py-3 px-4 bg-[#F9FBFC] flex rounded-lg text-xs'>
                  <StatusIconPrimary />

                  {item.status === OrderStatus.已完成 && (
                    <>
                      {(item.user_estimate && (
                        <View className='text-success flex items-center'>
                          <Icon name='checked' className=' mr-1' />
                          已完成
                        </View>
                      )) || (
                        <View className=' text-primary flex items-center'>
                          <Tag
                            type='warning'
                            className=' text-[20px] text-white mr-2 font-semibold'
                          >
                            ·完成评价可得{item.points}积分
                          </Tag>
                          <Icon name='thumb-circle' className=' mr-1' />
                          待评价
                        </View>
                      )}
                    </>
                  )}

                  {item.status === OrderStatus.已预约 && (
                    <>
                      <View
                        className='w-[162px] h-[36px] leading-[36px] pl-[16px] text-xs text-white mr-1'
                        style={{
                          backgroundImage: `url(https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/icon-warn-look.svg)`,
                          backgroundSize: '100% 100%',
                        }}
                        onClick={(e) => {
                          e.stopPropagation();
                          setAppointmentRecord(item);
                          openAppointSuccess();
                        }}
                      >
                        查看核销码
                      </View>
                      <View className='text-warn flex items-center'>
                        <Icon name='checked' className=' mr-1' />
                        已预约
                      </View>
                    </>
                  )}

                  {item.status === OrderStatus.待预约 && (
                    <View className=' text-warn flex items-center'>
                      <Icon name='clock' className=' mr-1' />
                      待预约
                    </View>
                  )}

                  {item.status === OrderStatus.已作废 && (
                    <View className=' text-gary4 flex items-center'>
                      <Icon name='clear' className=' mr-1' />
                      已取消
                    </View>
                  )}
                </View>
              </View>
            ))}
          </View>
        </Tab>
        {/* <Tab
          title={
            <>
              <View>充值订单
                 {Boolean(orderCount?.charge) && (
                  <Tag
                    type='danger'
                    textColor='white'
                    round
                    className=' absolute right-1 top-1'
                  >
                    {orderCount?.charge}
                  </Tag>
                )}
              </View>

            </>
          }
        >
          <View className='p-2'>
            {Boolean(!charge?.length) && (
              <View className='py-[180px]'>
                <Empty
                  icon={
                    <Image
                      src='https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/status-2.png'
                      className=' w-[381px] h-[311px] block -mb-[50px]'
                    />
                  }
                  title='暂无充值订单'
                  desc='暂时没有充值记录'
                >
                  <Button
                    type='primary'
                    className='w-[420px]'
                    onClick={() => {
                      Taro.navigateTo({
                        url: '/pages/my/bangdou/index',
                      });
                    }}
                  >
                    去查看
                  </Button>
                </Empty>
              </View>
            )}

            {charge?.map((item) => (
              <View key={item.id} className='mb-2'>
                <View className='p-3 px-4 bg-white rounded-lg'>
                  <View className='flex text-black items-center mb-2'>
                    <Text className='mr-auto font-bold text-[36px]'>
                      帮豆充值
                    </Text>
                    <Text className=' text-2xl font-bold leading-none mr-1'>
                      {item.beans}
                    </Text>
                    <Text className=' text-xs'>帮豆</Text>
                  </View>
                  <Text className=' text-xs text-gary3 block mt-1'>
                    订单编号：{item.no}
                  </Text>
                  <Text className=' text-xs text-gary3 block mt-1'>
                    创建时间：{item.create_time}
                  </Text>
                </View>
                <View className='py-3 px-4 bg-[#F9FBFC] flex rounded-lg text-xs'>
                  <StatusIconPrimary />
                  {item.status === 0 && (
                    <View className='text-warn flex items-center'>
                      <Icon name='clock' className=' mr-1' />
                      审核中
                    </View>
                  )}

                  {item.status === 1 && (
                    <View className='text-success flex items-center'>
                      <Icon name='checked' className=' mr-1' />
                      已完成
                    </View>
                  )}

                  {item.status === 2 && (
                    <View className=' text-gary4 flex items-center'>
                      <Icon name='clear' className=' mr-1' />
                      已驳回
                    </View>
                  )}
                </View>
              </View>
            ))}
          </View>
        </Tab> */}
      </Tabs>

      {renderSuccessNode()}
      {renderInvitaion()}
      {renderServiceNode()}
    </>
  );
}
